package com.uu.safeguard.controller;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.uu.safeguard.common.Constant;
import com.uu.safeguard.result.Result;
import com.uu.safeguard.result.ResultFactory;
import com.uu.safeguard.service.MemberService;
import com.uu.safeguard.utils.DbUtil;
import com.uu.safeguard.utils.JwtUtil;
import com.uu.safeguard.utils.WechatUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Validated
@RequestMapping("/login")
public class LoginController {
    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Resource
    MemberService memberService;


    @RequestMapping(path = "/401")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result unauthorized() {
        return ResultFactory.buildResult(401,"无权限访问",null);
    }

    /*@RequestMapping(path = "/redirect")
    public void redirect(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setStatus(301);
        response.sendRedirect("http://www.baidu.com");
    }*/

    /*@RequestMapping(path = "/test")
    public Result test(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map data = new HashMap();
        data.put("190827161537",JwtUtil.sign("190827161537", Constant.TOKEN_SECRET));
        return ResultFactory.buildSuccessResult(data);
    }*/

    //微信登录
    @PostMapping("/wechat")
    public Result wechat(String code, String appid) throws UnsupportedEncodingException {

        if(code == null || code.equals("")){
            return ResultFactory.buildFailResult("code有误");
        }
        if(appid == null || appid.equals("")){
            return ResultFactory.buildFailResult("平台编号有误");
        }

        DbUtil db = new DbUtil();

        Map platform = db.table("platform").where(new ArrayList(){{
            add(new ArrayList(){{
                add("wechat_appid");
                add("=");
                add(appid);
            }});
        }}).find("sn,wechat_appid,wechat_appsecret,new_member_free_money");

        String platform_sn = platform.get("sn").toString();
        String secret = platform.get("wechat_appsecret").toString();
        JSONObject userInfo = WechatUtil.getUserInfo(code, appid, secret);

        if(!userInfo.containsKey("openid")){
            return ResultFactory.buildFailResult("获取用户信息失败");
        }

        Map member = new HashMap();
        member.put("avatar",userInfo.get("headimgurl"));
        member.put("nickname",userInfo.get("nickname"));
        member.put("sex",userInfo.get("sex"));
        member.put("province",userInfo.get("province"));
        member.put("city",userInfo.get("city"));
        member.put("country",userInfo.get("country"));
        member.put("wechat_openid",userInfo.get("openid"));
        if(userInfo.get("unionid") != null){
            member.put("wechat_unionid",userInfo.get("unionid"));
        }
        member.put("type","1");


        String memberSn = memberService.otherLogin(member, platform);
        if(StringUtils.isNotBlank(memberSn)){
            String token = JwtUtil.sign(memberSn, Constant.TOKEN_SECRET);
            List roles = memberService.getRoles(memberSn);

            Map data = new HashMap();
            data.put("token",token);
            data.put("roles",roles);
            return ResultFactory.buildSuccessResult(data);
        }

        return ResultFactory.buildFailResult("获取用户信息失败");

    }


    //支付宝
    @PostMapping("/alipay")
    public Result alipay(String code, String appid) throws Exception {

        if(code == null || code.equals("")){
            return ResultFactory.buildFailResult("code有误");
        }
        if(appid == null || appid.equals("")){
            return ResultFactory.buildFailResult("平台编号有误");
        }

        DbUtil db = new DbUtil();
        Map platform = db.table("platform").where(new ArrayList(){{
            add(new ArrayList(){{
                add("alipay_appid");
                add("=");
                add(appid);
            }});
        }}).find("sn,alipay_appid,alipay_app_private_key,alipay_public_key,new_member_free_money");
        String platform_sn = platform.get("sn").toString();

        String alipay_app_private_key = platform.get("alipay_app_private_key").toString();
        String alipay_public_key = platform.get("alipay_public_key").toString();
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appid, alipay_app_private_key, "json", "UTF-8", alipay_public_key , "RSA2");
        AlipaySystemOauthTokenRequest codeRequest = new AlipaySystemOauthTokenRequest();
        codeRequest.setCode(code);
        codeRequest.setGrantType("authorization_code");
        AlipayUserInfoShareRequest userInfoShareRequest = new AlipayUserInfoShareRequest();
        AlipayUserInfoShareResponse userinfoShareResponse;
        try {
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(codeRequest);
            String auth_token = oauthTokenResponse.getAccessToken();
            userinfoShareResponse = alipayClient.execute(userInfoShareRequest, auth_token);
            String body = userinfoShareResponse.getBody();
        } catch (AlipayApiException e) {
            //处理异常
            e.printStackTrace();
            return ResultFactory.buildFailResult("获取用户信息失败");
        }


        Map member = new HashMap();
        member.put("avatar",userinfoShareResponse.getAvatar());
        member.put("nickname",userinfoShareResponse.getNickName());
        if(userinfoShareResponse.getCity().equals('m')){
            member.put("sex",1);
        }else if(userinfoShareResponse.getCity().equals('f')){
            member.put("sex",2);
        }else{
            member.put("sex",0);
        }
        member.put("province",userinfoShareResponse.getProvince());
        member.put("city",userinfoShareResponse.getCity());
        member.put("country","中国");
        member.put("alipay_userid",userinfoShareResponse.getUserId());
        member.put("type","2");


        String memberSn = memberService.otherLogin(member, platform);
        if(StringUtils.isNotBlank(memberSn)){
            List roles = memberService.getRoles(memberSn);
            String token = JwtUtil.sign(memberSn, Constant.TOKEN_SECRET);
            Map data = new HashMap();
            data.put("token",token);
            data.put("roles",roles);
            return ResultFactory.buildSuccessResult(data);
        }

        return ResultFactory.buildFailResult("获取用户信息失败");


    }

}

